package ink.ykb.droolstest.config;

import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

/**
 * 全局处理异常
 */
@Slf4j
@ControllerAdvice
public class GlobalErrorController {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class,MissingServletRequestParameterException.class})
    @ResponseBody
    public  ResponseMsg<String> bindExceptionHandler(Exception e) {
        
        String code = null;
        String field = null;
        if(e instanceof BindException){
            BindException e1 =  (BindException)e;
            code = e1.getBindingResult().getFieldError().getDefaultMessage();
            field = e1.getBindingResult().getFieldError().getField();
        }else if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException e1 = (MethodArgumentNotValidException)e;
            field = e1.getBindingResult().getFieldError().getField();
            code = e1.getBindingResult().getFieldError().getDefaultMessage();
        }else if(e instanceof MissingServletRequestParameterException){
          MissingServletRequestParameterException e1 = (MissingServletRequestParameterException)e;
          field = e1.getMessage();
          code = e1.getMessage();
        }
        
        log.error("参数校验失败：{}" ,field);
        return new ResponseMsg<>(ResponseMsg.CODE_FAIL,code);
        
    }

	@ExceptionHandler(ServiceException.class)
    public @ResponseBody ResponseMsg<Object> serviceException(ServiceException e) {
        log.error("异常信息： \n编号：{}\n消息：{}\n数据：{}\n位置：{}",
        		e.getCode(),
        		e.getMessage(),
        		e.getData()!= null?JSONObject.toJSONString(e.getData()):"",
        		(e.getStackTrace()!=null && e.getStackTrace().length > 0)?e.getStackTrace()[0].toString():e.getStackTrace());
        
        return new ResponseMsg<>(e.getCode(),e.getMessage(),e.getData());
    }

	@ExceptionHandler(Exception.class)
    public @ResponseBody ResponseMsg<String> exception(Exception e) {
        log.error("未知错误",e);
        return new ResponseMsg<>(ResponseMsg.CODE_UNKNOWN_ERROR,"未知异常",e.getMessage());
    }
}
